<template>
    <div>
        <el-drawer v-model="drawer" title="用户信息" :with-header="true" @open="getUserInfo" @closed="resetUserInfo">
            <template #default>
                <el-row>
                    <el-col :span="4" class="avatar_label">头像</el-col>
                    <el-col :span="20"><el-avatar :src="userInfo.avatar" /></el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">邮箱</el-col>
                    <el-col :span="20">{{ userInfo.email }}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">ID</el-col>
                    <el-col :span="20">{{ userInfo.id }}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">用户名</el-col>
                    <el-col :span="20">{{ userInfo.name }}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="4">简介</el-col>
                    <el-col :span="20">{{ userInfo.intro }}</el-col>
                </el-row>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
// 引入接口
import { reqViewUser } from "@/api/user";
import type { userInfoResponse } from "@/api/user/type";
// 定义抽屉的显示与隐藏
const drawer = ref<boolean>(false);
// 获取传入的参数
const props = defineProps({
    visible: {
        type: Boolean,
        required: true,
    },
    userId: {
        type: [String, Number],
        required: true,
    },
});
// 监听visible的变化
watch(
    () => props.visible,
    (newVal: boolean) => {
        drawer.value = newVal;
    },
);
const emit = defineEmits(["update:visible"]);
// 监听drawer的变化，并更新visible的值
watch(
    () => drawer.value,
    (newVal: boolean) => {
        emit("update:visible", newVal);
    },
);

// 获取用户信息
const userInfo = ref<userInfoResponse>({
    id: -1,
    name: "",
    email: "",
    avatar: "",
    intro: "",
});
const getUserInfo = async () => {
    if (props.userId === -1) {
        return;
    }
    const res = await reqViewUser(props.userId);
    if (res.code === 200 && typeof res.data === "object") {
        userInfo.value = res.data;
    } else {
        ElMessage.error(res.data as string);
    }
};

// 抽屉关闭时应该清除用户信息
const resetUserInfo = () => {
    userInfo.value = {
        id: -1,
        name: "",
        email: "",
        avatar: "",
        intro: "",
    };
};
</script>

<style lang="scss" scoped>
.el-row {
    // 配置行的下边距，控制布局
    margin-bottom: 20px;

    .avatar_label {
        display: flex;
        align-items: center;
    }
}
</style>
